package pkg

import (
	"bytes"
	"context"
	"encoding/json"
	"srv/basic/config"
	__ "srv/basic/proto"
	"srv/handler/models"
	"sync"

	"github.com/elastic/go-elasticsearch/v7/esapi"
	"log"
	"strconv"
)

func EsAdd() {
	var wg sync.WaitGroup
	var o models.Order
	list, err := o.OrderList()
	if err != nil {
		return
	}
	for _, order := range list {
		wg.Add(1)

		go func(order *models.Order) {
			defer wg.Done()

			// Build the request body.
			data, err := json.Marshal(order)
			if err != nil {
				log.Fatalf("Error marshaling document: %s", err)
			}

			// Set up the request object.
			req := esapi.IndexRequest{
				Index:      "order",
				DocumentID: strconv.Itoa(int(order.Id)),
				Body:       bytes.NewReader(data),
				Refresh:    "true",
			}

			// Perform the request with the client.
			res, err := req.Do(context.Background(), config.Es)
			if err != nil {
				log.Fatalf("Error getting response: %s", err)
			}
			defer res.Body.Close()

		}(order)
	}
	wg.Wait()
}

func EsList(keyword string) (EsList []*__.EsList) {
	var buf bytes.Buffer
	var query map[string]interface{}
	if keyword == "" {
		query = map[string]interface{}{
			"query": map[string]interface{}{
				"match": map[string]interface{}{
					"origin": keyword,
				},
			},
		}
	} else {
		query = map[string]interface{}{
			"query": map[string]interface{}{
				"match_all": map[string]interface{}{},
			},
		}
	}

	if err := json.NewEncoder(&buf).Encode(query); err != nil {
		log.Fatalf("Error encoding query: %s", err)
	}

	// Perform the search request.
	res, err := config.Es.Search(
		config.Es.Search.WithContext(context.Background()),
		config.Es.Search.WithIndex("order"),
		config.Es.Search.WithBody(&buf),
		config.Es.Search.WithTrackTotalHits(true),
		config.Es.Search.WithPretty(),
	)
	if err != nil {
		log.Fatalf("Error getting response: %s", err)
	}
	defer res.Body.Close()
	var r map[string]interface{}
	if err := json.NewDecoder(res.Body).Decode(&r); err != nil {
		log.Fatalf("Error parsing the response body: %s", err)
	}
	for _, hit := range r["hits"].(map[string]interface{})["hits"].([]interface{}) {
		source := hit.(map[string]interface{})["_source"].(map[string]interface{})

		id := source["Id"].(float64)
		userId := source["UserId"].(float64)
		model := source["Model"].(string)
		origin := source["Origin"].(string)
		end := source["End"].(string)

		EsList = append(EsList, &__.EsList{
			Origin: origin,
			End:    end,
			Model:  model,
			UserId: uint64(userId),
			Id:     uint64(id),
		})
	}
	return
}
